﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

public interface IJwtService
{
    string CreateTokenAsync(string username, string roles);
}

// 实现
public class JwtUtils : IJwtService
{
    public TokenOptions TokenOptions { get; }

    public JwtUtils(TokenOptions options)
    {
        TokenOptions = options;
    }

    public string CreateTokenAsync(string username, string roles)
    {
        // 添加一些需要的键值对
        Claim[] claims = new[]
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, roles)
        };

        var keyBytes = Encoding.UTF8.GetBytes(TokenOptions.SecretKey);
        var creds = new SigningCredentials(new SymmetricSecurityKey(keyBytes),
            SecurityAlgorithms.HmacSha256);

        var jwtSecurityToken = new JwtSecurityToken(
            issuer: TokenOptions.Issuer, // 签发者
            audience: TokenOptions.Audience, // 接收者
            claims: claims, // payload
            expires: DateTime.Now.AddMinutes(TokenOptions.ExpireMinutes), // 过期时间
            signingCredentials: creds); // 令牌

        string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        return token;
    }
}